# GameOverScreen.gd
extends CanvasLayer

@onready var score_label: Label = $Panel/MarginContainer/VBoxContainer/ScoreLabel
@onready var time_label: Label = $Panel/MarginContainer/VBoxContainer/TimeLabel
@onready var restart_button: Button = $Panel/MarginContainer/VBoxContainer/RestartButton
@onready var menu_button: Button = $Panel/MarginContainer/VBoxContainer/MenuButton

func _ready():
	hide() # Start hidden
	SignalBus.game_over.connect(show_screen)
	restart_button.pressed.connect(_on_restart_button_pressed)
	menu_button.pressed.connect(_on_menu_button_pressed)
	print("GameOverScreen Ready")


func show_screen():
	# Retrieve final stats from GameManager
	score_label.text = "Final Score: %d" % GameManager.get_score()
	time_label.text = "Survived For: %s" % GameManager.format_time(GameManager.get_game_time())

	# TODO: Add meta currency earned calculation
	# Save game progress (meta currency, achievements)
	SaveManager.save_game()

	# Ensure game is fully paused (should be already, but double-check)
	get_tree().paused = true
	show()


func _on_restart_button_pressed():
	# Ensure game is unpaused before changing scene
	get_tree().paused = false
	# Reload the main game scene
	# This assumes your main game logic is in MainGame.tscn
	var error = get_tree().change_scene_to_file("res://scenes/main/MainGame.tscn")
	if error != OK:
		printerr("Failed to change scene to MainGame:", error)


func _on_menu_button_pressed():
	# Ensure game is unpaused before changing scene
	get_tree().paused = false
	# Go back to the main menu
	var error = get_tree().change_scene_to_file("res://scenes/main/MainMenu.tscn")
	if error != OK:
		printerr("Failed to change scene to MainMenu:", error)